from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import Session, sessionmaker

from pathlib import Path

from app.config import config
from app.web.models.BaseModel import Base
from app.web.models.JobSeeker import JobSeeker
from app.web.models.Recruiter import Recruiter

# SQLite Config
# SQLALCHEMY_DATABASE_URL = "sqlite:///:memory:"
db_path = config.root_path / "tests" / "ai-resume.db"
SQLALCHEMY_DATABASE_URL = "sqlite:///" + str(db_path)
print(f"SQLALCHEMY_DATABASE_URL: {SQLALCHEMY_DATABASE_URL}")
engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}#, echo=True
)
inspector = inspect(engine)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def init_database():
    create_job_seeker_data = False
    create_recruiter_data = False
    if not inspector.has_table('job_seeker'):
        create_job_seeker_data = True
    if not inspector.has_table('recruiter'):
        create_recruiter_data = True
    # 自动创建表结构
    Base.metadata.create_all(bind=engine)
    with Session(engine) as session:
        tables = []
        if create_job_seeker_data:
            test_job_seeker = JobSeeker(name="张三", age=30)
            tables.append(test_job_seeker)
        if create_recruiter_data:
            test_recruiter = Recruiter(name="李四", company="XXX科技有限责任公司")
            tables.append(test_recruiter)
        if len(tables) > 0:
            session.add_all(tables)
            session.commit()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
